 package com.controller;

import java.io.*;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.model.Message;
import com.thread.MsgThread;
import com.util.LogUtil;
import com.model.Result;
import com.model.SaveOffice;
import com.service.LoginService;
import com.util.PagedRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.model.Login;
import com.service.SaveOfficeService;
import com.util.ExportThread;
import com.util.PagedResult;
import org.springframework.web.bind.annotation.ResponseBody;
import org.json.JSONObject;
import org.springframework.web.socket.TextMessage;
import sys.model.UserEmail;

 @Controller
@RequestMapping("/in")
public class LoginController {
	 @Resource
	 LoginService loginService;
	 @Autowired
	 SaveOfficeService saveofficeService;
		@RequestMapping("/login")
	public	String login(){
			return "login";
		}
	@RequestMapping("/web")
	public	String web(){
		return "jsp/test/websocket";
	}
	 @RequestMapping("/aaa")
	 public	String aaaa(){
		 return "jsp/anser/aaaaa";
	 }

	 @RequestMapping("/au")
	 @ResponseBody
	 public	String au(){
		 Message msg=new Message("","",null,"1","","asasas","");
		 JSON.toJSONString(msg);
		 (new MsgThread(new UserEmail())).start();
		 MsgHandler.sendMessageToUser("userid-1",new TextMessage("{\"id\":1,\"msg\":{\"content\":\"11111111111111111111111111\",\"ctime\":1488937061000,\"ctimeToFullString\":\"2017-03-08 09:37:41\",\"timeAgo\":\"24 小时 前\",\"title\":\"给自己的一封\"},\"msgid\":1,\"readstatus\":false,\"recever\":\"根哥\",\"receverid\":1,\"sender\":\"根哥\",\"senderid\":1}"));
		 return "{status:true}";
	 }
	/////问卷111
	 @RequestMapping("/anser")
	 public	String anser(){
		 return "jsp/anser/anser";
	 }
     @RequestMapping("/file")
     public	String file(){
         return "jsp/test/file";
     }
	 @RequestMapping("/anserTest")
	 public	String anserTest(){
		 return "jsp/test/anserTest";
	 }
	 @ResponseBody
	 @RequestMapping("/Result")
	 public	String submit(Result r){
		 System.out.println(r.toString());
         int i=loginService.anser_insert(r);
        if(i>0) System.out.println("问卷结果插入成功!");
         return JSON.toJSONString("true");
	 }

     @RequestMapping("/getAnserpage")
     public	String getAnserpage(){
         return "jsp/anser/getanser";
     }
     @ResponseBody
     @RequestMapping("/getAnserAll")
     public	String getAnserAll(){
         List<Result> list=loginService.getAnserAll();
         return JSON.toJSONString(list);
     }









	 @RequestMapping("/web2")
	 public	String web2(){
		 return "jsp/test/test2";
	 }
		@RequestMapping("/ztree")
		public	String ztree(){
				return "ztree";
			}
		@RequestMapping("/index")
		public	String index(){
				return "index";
			}
		@RequestMapping("/hello")
		public	String hello(){
			return "hello";
		}
		@RequestMapping("/moveEchat")
		public String moveEchat(){
			return "moveEchat";
	}
		@RequestMapping(value="/echarts",produces = "text/html;charset=UTF-8")
		@ResponseBody
		public String echarts() throws JSONException{
			
			List<SaveOffice> list=saveofficeService.selectAll();
			JSONArray json = JSONArray.fromObject(list);
			return json.toString();
			
		}
		@RequestMapping("/getAllLogin")
		@ResponseBody
		public String getAllLogin(PagedRequest pagedRequest){
			LogUtil.info("分页参数:"+	pagedRequest.getPage());
	    	LogUtil.info("分页页数:"+	pagedRequest.getRows());
	    	LogUtil.info("排序序名:"+	pagedRequest.getSidx());
	    	LogUtil.info("排序方式:"+	pagedRequest.getSord());
	    	LogUtil.info("成功");
	    	
			PagedResult<Login> l_list = loginService.getAllLogin(pagedRequest);
			System.out.println(JSON.toJSONString(l_list));
			return   JSON.toJSONString(l_list);
			
			
		}
		
		
		
		@RequestMapping(value = "/update", method = { RequestMethod.POST,
				RequestMethod.GET })
		@ResponseBody
		public String update(HttpServletRequest request,HttpServletResponse response) throws Exception {
			int id = Integer.valueOf(request.getParameter("id"));

			if(id == 0){
				return null;
			}

			JSONObject json = new JSONObject();
			
			Login login =new Login();
			login.setId(id);
			login.setUserName(request.getParameter("userName"));
			login.setPassWord(request.getParameter("passWord"));
			LogUtil.info("bean1:"+login);
			if(loginService.update(login)<1){

				json.put("status", "false");
				json.put("msg", "修改错误");
				LogUtil.info("json:"+json.toString());
				return json.toString();
			}
			json.put("status", "true");
			json.put("msg", "修改成功");
			LogUtil.info("json:"+json.toString());
			return json.toString();
		}
		//验证用户名
		@RequestMapping(value = "/vaName", method = { RequestMethod.POST,
				RequestMethod.GET })
		@ResponseBody
		public String vaName(HttpServletRequest request,HttpServletResponse response) throws Exception {
			String userName=request.getParameter("userName");
			JSONObject json = new JSONObject();
			if(!userName.equals("shugen"))
			json.put("data", "true");
			else json.put("data", "false");
			LogUtil.info("验证结果:"+json.toString());
			return json.toString();
		}
		@RequestMapping(value = "/update2", method = { RequestMethod.POST,
				RequestMethod.GET })
		public String update2(HttpServletRequest request,HttpServletResponse response) throws Exception {
			
			response.setContentType("text/html;charset=UTF-8");
			int id = Integer.valueOf(request.getParameter("id"));
			if(id == 0){
				return null;
			}
			JSONObject json = new JSONObject();
			Login login =new Login();
			login.setId(id);
			login.setUserName(request.getParameter("userName"));
			login.setPassWord(request.getParameter("passWord"));
			LogUtil.info("bean1:"+login);
			if(loginService.update(login)<1){

				json.put("status", "false");
				json.put("msg", "修改错误");
				  response.getWriter().print(json.toString());
				return null;
			}
			json.put("status", "true");
			json.put("msg", "修改成功!!");
			LogUtil.info("json:"+json.toString());
			  response.getWriter().print(json.toString());
			return null;
		}
					
		@RequestMapping(value = "/add", method = { RequestMethod.POST,
				RequestMethod.GET })
		public String add(HttpServletRequest request,HttpServletResponse response) throws Exception {
			
			response.setContentType("text/html;charset=UTF-8");
			JSONObject json = new JSONObject();
			Login login =new Login();
			login.setUserName(request.getParameter("userName"));
			login.setPassWord(request.getParameter("passWord"));
			LogUtil.info("bean1:"+login);
			
			if(loginService.add(login)<1){

				json.put("status", "false");
				json.put("msg", "添加错误");
			
				  response.getWriter().print(json.toString());
				return null;
			}
			int  id=login.getId();
			json.put("status", "true");
			json.put("msg", "添加成功");
			json.put("id", id);
			LogUtil.info("json:"+json.toString());
			  response.getWriter().print(json.toString());
			return null;
		}
		@RequestMapping(value = "/delete", method = { RequestMethod.POST,
				RequestMethod.GET })
		public String delete(HttpServletRequest request,HttpServletResponse response) throws Exception {
			
			response.setContentType("text/html;charset=UTF-8");
			JSONObject json = new JSONObject();
			int id = Integer.valueOf(request.getParameter("id"));
			
			if(loginService.delete(id)<1){

				json.put("status", "false");
				json.put("msg", "删除错误");
				  response.getWriter().print(json.toString());
				return null;
			}
			json.put("status", "true");
			json.put("msg", "删除成功");
			LogUtil.info("json:"+json.toString());
			  response.getWriter().print(json.toString());
			return null;
		}
		@RequestMapping(value = "/ext", method = { RequestMethod.POST,
				RequestMethod.GET })
		public String ext(Login l,HttpServletRequest request,HttpServletResponse response) throws Exception {
			  String fileName="excel文件";//  文件名
			  ByteArrayOutputStream os = new ByteArrayOutputStream(); 
			  loginService.ext().write(os);   
		        byte[] content = os.toByteArray();  //二进制输出流   转成 二进制字节数组
		        InputStream is = new ByteArrayInputStream(content);  //变成输入流
		        // 设置response参数，可以打开下载页面
		        response.reset();
		        response.setContentType("application/vnd.ms-excel;charset=utf-8");
		        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		        ServletOutputStream out = response.getOutputStream();
		        BufferedInputStream bis = null;
		        BufferedOutputStream bos = null;
		        try {
		            bis = new BufferedInputStream(is);
		            bos = new BufferedOutputStream(out);
		            byte[] buff = new byte[2048];
		            int bytesRead;
		            // Simple read/write loop.
		            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
		                bos.write(buff, 0, bytesRead);
		            }
		        } catch (final IOException e) {
		            throw e;
		        } finally {
		            if (bis != null)
		                bis.close();
		            if (bos != null)
		                bos.close();
		        }
		        return null;
		    }
		@RequestMapping("/thread")
		public void  threadTest(){
			Login l=new Login();
			l.setId(1);
			l.setUserName("shugen");
			(new ExportThread(l)).start();
		}
		
		@RequestMapping("/down")
		public ResponseEntity<byte[]> down() throws IOException{
			HttpHeaders headers = new HttpHeaders();  
			String filePath = null;  
			filePath = "D:/QMDownload/QQLog_1470299096.csv";  
			File file=new File(filePath);
			String fileName=file.getName();
			headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "iso-8859-1"));  
			return (new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED)); 
			
			
		}
}
